# import pytest
from selenium import webdriver
import unittest, time
from contrast import ImageCompare
# from ddt import ddt,data
from public import *
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import shutil
import datetime
import logging
from logger import *
import os
# from PIL import ImageGrab
import requests
import xlrd,xlwt
from xlutils.copy import copy
from test_send_email import *
import dingtalkchatbot.chatbot as cb

# class TestAutomation:
import sys
sys.setrecursionlimit(10000)

def set_sum(i):
    sum = i
    return sum


file_name =None
DEV_NAME = "3号样机"


def create_excel(d):
    global file_name
    ws = xlwt.Workbook()
    sheet = ws.add_sheet("CBCT曝光上传")
    sheet.write(0,0,'虚拟驱动自动化测试')
    sheet.write(0, 1, "设置运行次数")
    sheet.write(1, 1, "{}".format(d))
    sheet.write(2, 1, "{}".format(d))
    sheet.write(3, 1, "{}".format(d))
    sheet.write(0, 2, "实际运行次数")
    sheet.write(0, 3, "上传成功次数")
    sheet.write(0, 4, "上传失败次数")
    sheet.write(0, 5, "卡住次数")
    sheet.write(1, 0, "CT上传")
    sheet.write(2, 0, "PX上传")
    sheet.write(3, 0, "DX上传")
    file_name =".\\reports\\CBCT_上传测试{}.xls".format(time.strftime('%Y-%m-%d-%H'))
    ws.save(file_name)


def write_excel(a,b,value):
    data = xlrd.open_workbook(file_name)
    workbook = copy(data)
    sheet_write = workbook.get_sheet(0)
    value = str(value)
    sheet_write.write(a,b,value)
    workbook.save(file_name)



def login_():
    driver = webdriver.Chrome()
    driver.get('http://127.0.0.1:8189/#/')
    driver.maximize_window()
    time.sleep(3)
    driver.find_element_by_xpath('//input[@class="yg-input__inner" and @placeholder="请输入手机号码"]').send_keys("18576787614")  # 输入手机号
    driver.find_element_by_xpath('//input[@class="yg-input__inner" and @placeholder="请输入密码"]').send_keys('123456')  # 输入密码
    driver.find_element_by_xpath('//div[@class="zh_postForm"]').click()  # 点击登录
    return driver

# global i


ct_a =0 #上传成功
ct_b =0 #上传失败
ct_c =0 #准备进度卡住

def create_contexts(path):
    isExists = os.path.exists(path)
    if not isExists:
        print(path)
        os.mkdir(path)
        return path

    else:
        print('已存在！')
        return path

def create_test_contexts(path):
    isExists = os.path.exists(path)
    if not isExists:
        print(path)
        os.makedirs(path)
        return path

    else:
        print('已存在！')
        return path

def get_current_path():
    path = os.path.split(os.path.realpath(__file__))[0]
    return path


def send_to_dingtalk(dev, mode, count):
    # 钉钉群机器人链接
    webhook = "https://oapi.dingtalk.com/robot/send?access_token=e509b050fa96e3e9e03489415a91a362fb7f763b6e659054ac9ca8753ac3d226"
    robot = cb.DingtalkChatbot(webhook)
    robot.send_text(msg="自动化测试：{3}, {0}, {1}, 次数{2}, 进度卡住！！！".format(dev, mode, str(count), str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))


def test_01_CT_shooting(i,c,path,path2):
    global DEV_NAME
    logging.info('CT开始时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
    logging.info('test_01_CT_shooting第{}次'.format(i))
    write_excel(1,2,i)
    if c:
        driver = c
        # logging.info('test_01_CT_shooting_第{}次'.format(i))
        time.sleep(8)
        driver.find_element_by_xpath('//div[text()="登记"]').click()  # 进入登记页
        time.sleep(1)
        patient_name = random_name()
        driver.find_element_by_xpath('//input[@placeholder="患者姓名" and @class="yg-input__inner" ]').send_keys("{}".format(patient_name))  # 输入患者姓名参数化
        time.sleep(1)
        driver.find_element_by_xpath('//div[@id="cbctCT"]').click()  # 选择拍摄模式
        time.sleep(1)
        driver.find_element_by_xpath('//div[@class="check-in-wrap"]/following-sibling::div[1]//div[2]').click()  # 点击下一步
        time.sleep(2)
        driver.find_element_by_xpath('//div[@id="app"]/div[1]/div[1]/table[1]/tr[2]/td[1]/div[4]/div[3]').click()  # 10X9
        # time.sleep(1)
        # driver.find_element_by_xpath('//div[@id="app"]/div[1]/div[1]/table[1]/tr[2]/td[1]/div[4]/div[3]').click()  # 15X9
        # time.sleep(1)
        # driver.find_element_by_xpath('//div[@id="app"]/div[1]/div[1]/table[1]/tr[2]/td[1]/div[5]/div[3]').click()  # 0.3体素
        time.sleep(2)
        driver.find_element_by_xpath('//button[@id="cbctOkct"]').click()  # 点击确确定

        try:
            progress_locator = (By.XPATH, '//div[contains(text()," 准备完成")]')  # 等待准备完成元素可见
            WebDriverWait(driver, 90, 1).until(EC.visibility_of_element_located(progress_locator))
            time.sleep(1)
            driver.find_element_by_xpath('//div[@id="cbctFinishct"]').click()  # CT点击下一步
            time.sleep(2)
            shutil.copy('C:\\CTDebug\\HandSwitch\\HandSwitchOn.txt', 'C:\\CTDebug')  # 复制手闸文件到CTDebug目录
            # time.sleep(130)  # 等待采集曝光完成
            # dic_file = create_contexts(path)  #
            # filepath = '{}\\{}.png'.format(dic_file,str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
            # driver.save_screenshot(filepath)
            # time.sleep(3)

            # 智能等待
            WebDriverWait(driver, 1200, 3).until(EC.visibility_of_element_located((By.XPATH,'//span[@class="nsel close-btn"]')))
            WebDriverWait(driver, 1200, 3).until_not(EC.visibility_of_element_located((By.XPATH, '//div[@class="circle_proc"]')))
            time.sleep(2)
            driver.find_element_by_xpath('//span[@class="nsel close-btn"]').click()  # CT叉掉元素
            WebDriverWait(driver, 120, 3).until(EC.visibility_of_element_located((By.XPATH, '//div[text()="已检查"]')))
            driver.find_element_by_xpath('//div[text()="已检查"]').click()  # 已检查元素
            # try:
            #             #     loc_upload = (By.XPATH, '//div[contains(text(),"已上传")]')
            #             #     if WebDriverWait(driver, 150, 1).until(EC.visibility_of_all_elements_located(loc_upload)):
            #             #         logging.info('CT上传成功')
            #             #         global ct_a
            #             #         ct_a += 1
            #             #         write_excel(1, 3, ct_a)
            #             # except:
            #             #     logging.info('CT上传失败')
            #             #     global ct_b
            #             #     ct_b += 1
            #             #     write_excel(1, 4, ct_b)

            logging.info('CT结束时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
            return driver
        except:
            dics_files = create_test_contexts(path2)
            error_filepath = '{}\\{}.png'.format(dics_files,str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
            driver.save_screenshot(error_filepath)
            global ct_c
            ct_c +=1
            write_excel(1,5,ct_c)
            logging.error("CT{}进度卡住！！！".format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
            send_to_dingtalk(DEV_NAME, "CT", i)
            # driver.quit()




px_a =0
px_b =0
px_c =0 #准备进度卡住


def test_02_Panoramic_shooting(i,a,path,path2):
    global DEV_NAME
    driver2 = a
    logging.info('PX开始时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
    logging.info('PX第{}次'.format(i))

    write_excel(2,2,i)
    time.sleep(3)
    driver2.find_element_by_xpath('//div[text()="登记"]').click()
    time.sleep(1)
    patient_name2 = random_name()
    driver2.find_element_by_xpath('//input[@placeholder="患者姓名" and @class="yg-input__inner" ]').send_keys("{}".format(patient_name2))  # 输入患者姓名参数化
    driver2.find_element_by_xpath('//div[@id="cbctPX"]').click() #全景模式
    time.sleep(1)
    driver2.find_element_by_xpath('//div[@class="check-in-wrap"]/following-sibling::div[1]//div[2]').click()   # 选择模式后的下一步
    time.sleep(3)
    driver2.find_element_by_xpath('//button[@id="cbctOkpano"]').click()  #点击确定
    '''去曝光'''

    try:
        # time.sleep(60)
        progress_locator = (By.XPATH, '//div[contains(text()," 准备完成")]')  #等待准备完成元素可见
        WebDriverWait(driver2,150,1).until(EC.visibility_of_element_located(progress_locator))
        time.sleep(1)
        driver2.find_element_by_xpath('//div[@id="cbctFinishceph"]').click()  #全景下一步
        time.sleep(2)
        shutil.copy('C:\\CTDebug\\HandSwitch\\HandSwitchOn.txt', 'C:\\CTDebug')  # 复制手闸文件到CTDebug目录
        # time.sleep(100)  # 全景曝光与采集时间
        # dic_file = create_contexts(path)  #
        # filepath = '{}\\{}.png'.format(dic_file, str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
        # # filepath = 'E:\\PXscreenshot\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
        # driver2.save_screenshot(filepath)
        logging.info('当前first时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        time.sleep(10)

        # 智能等待
        loc = (By.XPATH, '//div[@class="circle_proc"]')
        WebDriverWait(driver2, 1200, 3).until_not(EC.visibility_of_element_located(loc))
        time.sleep(2)
        driver2.find_element_by_xpath('//div[@id="cbctbcpano"]').click()  # 全景对勾元素确定
        WebDriverWait(driver2, 120, 3).until(EC.visibility_of_element_located((By.XPATH, '//div[text()="已检查"]')))
        driver2.find_element_by_xpath('//div[text()="已检查"]').click()  # 已检查元素
        # try:
        #     loc_upload = (By.XPATH, '//div[contains(text(),"已上传")]')
        #     if WebDriverWait(driver2,135, 1).until(EC.visibility_of_all_elements_located(loc_upload)):
        #         logging.info('PX上传成功')
        #         global px_a
        #         px_a += 1
        #         write_excel(2, 3, px_a)
        # except:
        #     global px_b
        #     px_b += 1
        #     write_excel(2, 4, px_b)
        #     logging.info('PX上传失败')
        logging.info('PX结束时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        return driver2

    except:
        logging.info('当前second时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        dics_files = create_test_contexts(path2)
        error_filepath = '{}\\{}.png'.format(dics_files, str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
        # error_filepath = 'E:\\PXscreenshot\\error\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
        driver2.save_screenshot(error_filepath)
        global px_c
        px_c += 1
        write_excel(2, 5, px_c)
        logging.error("PX{}进度卡住！！！".format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        send_to_dingtalk(DEV_NAME, "PX", i)
        # driver2.quit()


    # 头侧拍摄


dx_a =0
dx_b =0
dx_c =0  #准备进度卡住


def test_03_Head_side_shot(i,b,path,path2):
    global DEV_NAME
    drive3 = b
    logging.info('DX开始时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
    logging.info('DX第{}次'.format(i))

    write_excel(3,2,i)
    time.sleep(3)
    drive3.find_element_by_xpath('//div[text()="登记"]').click()
    time.sleep(1)
    patient_name3 = random_name()
    drive3.find_element_by_xpath('//input[@placeholder="患者姓名" and @class="yg-input__inner" ]').send_keys("{}".format(patient_name3)) # 输入患者姓名参数化
    drive3.find_element_by_xpath('//div[@id="cbctDX"]').click()  #头测模式
    time.sleep(1)
    drive3.find_element_by_xpath('//div[@class="check-in-wrap"]/following-sibling::div[1]//div[2]').click()  #选择模式下的下一步
    # time.sleep(2)
    WebDriverWait(drive3, 60, 3).until(EC.visibility_of_element_located((By.XPATH, '//div[@id="item2"]')))
    drive3.find_element_by_xpath('//div[@id="item2"]').click()  #选择全头颅模式
    time.sleep(3)
    drive3.find_element_by_xpath('//button[@id="cbctOkceph"]').click() #确定按钮

    try:
        progress_locator = (By.XPATH, '//div[contains(text()," 准备完成")]')  #等待准备完成元素可见
        WebDriverWait(drive3,150,1).until(EC.visibility_of_element_located(progress_locator))
        time.sleep(1)
        drive3.find_element_by_xpath('//div[@id="cbctFinishceph"]').click()  # 头测点下一步
        time.sleep(2)
        # 判断放手闸的提示语元素
        shutil.copy('C:\\CTDebug\\HandSwitch\\HandSwitchOn.txt', 'C:\\CTDebug')  # 复制手闸文件到CTDebug目录
        # time.sleep(100)     # 头测曝光与采集时间
        # dic_file = create_contexts(path)  #
        # filepath = '{}\\{}.png'.format(dic_file, str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
        # # filepath = 'E:\\DXscreenshot\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
        # drive3.save_screenshot(filepath)
        time.sleep(10)

        # 智能等待
        loc = (By.XPATH, '//div[@class="circle_proc"]')
        WebDriverWait(drive3, 1200, 3).until_not(EC.visibility_of_element_located(loc))
        time.sleep(2)
        drive3.find_element_by_xpath('//div[@id="cbctbcceph"]').click()  # 点击头测对勾元素确定
        WebDriverWait(drive3, 120, 3).until(EC.visibility_of_element_located((By.XPATH, '//div[text()="已检查"]')))
        drive3.find_element_by_xpath('//div[text()="已检查"]').click()  # 已检查元素
        # try:
        #     loc_upload = (By.XPATH, '//div[contains(text(),"已上传")]')
        #     if WebDriverWait(drive3, 30, 1).until(EC.visibility_of_all_elements_located(loc_upload)):
        #         logging.info('DX上传成功')
        #         global dx_a
        #         dx_a+=1
        #         write_excel(3,3,dx_a)
        # except:
        #     logging.info('DX上传失败')
        #     global dx_b
        #     dx_b += 1
        #     write_excel(3, 4, dx_b)
        logging.info('DX结束时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        return drive3

    except:
        dics_files = create_test_contexts(path2)
        error_filepath = '{}\\{}.png'.format(dics_files, str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
        # error_filepath = 'E:\\DXscreenshot\\error\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
        drive3.save_screenshot(error_filepath)
        global dx_c
        dx_c += 1
        write_excel(3, 5, dx_c)
        logging.error("DX{}进度卡住！！！".format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        send_to_dingtalk(DEV_NAME, "DX", i)
        # drive3.quit()


'''模扫'''
def test_04_Mode_scanning(i,d,path,path2):
    global DEV_NAME
    drive4 = d
    logging.info('MS开始时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
    logging.info('MS第{}次'.format(i))

    write_excel(4,2,i)
    time.sleep(3)
    drive4.find_element_by_xpath('//div[text()="登记"]').click()
    time.sleep(1)
    patient_name3 = random_name()
    drive4.find_element_by_xpath('//input[@placeholder="患者姓名" and @class="yg-input__inner" ]').send_keys("{}".format(patient_name3)) # 输入患者姓名参数化
    drive4.find_element_by_xpath('//div[@id="cbctMS"]').click()  #模扫模式
    time.sleep(1)
    drive4.find_element_by_xpath('//div[@class="check-in-wrap"]/following-sibling::div[1]//div[2]').click()  #选择模式下的下一步
    time.sleep(4)
    drive4.find_element_by_xpath('//button[@class="ok-btn m-b40 m-t205 userSelect bianseBorder"]').click() #确定按钮

    try:
        progress_locator = (By.XPATH, '//div[contains(text()," 准备完成")]')  #等待准备完成元素可见
        WebDriverWait(drive4,150,1).until(EC.visibility_of_element_located(progress_locator))
        time.sleep(1)
        drive4.find_element_by_xpath('//div[@class="bianseBorderto"]').click()  # 模扫点下一步
        time.sleep(2)
        # 判断放手闸的提示语元素
        shutil.copy('C:\\CTDebug\\HandSwitch\\HandSwitchOn.txt', 'C:\\CTDebug')  # 复制手闸文件到CTDebug目录
        # time.sleep(120)  # 模扫曝光与采集时间
        # dic_file = create_contexts(path)  #
        # filepath = '{}\\{}.png'.format(dic_file, str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))
        # # filepath = 'E:\\DXscreenshot\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
        # drive4.save_screenshot(filepath)

        # 智能等待
        WebDriverWait(drive4, 300, 3).until(
            EC.visibility_of_element_located((By.XPATH, '//span[@class="nsel close-btn"]')))
        logging.info("等待模扫预览对话框！{}".format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        WebDriverWait(drive4, 300, 3).until(
            EC.visibility_of_element_located((By.XPATH, '//div[@class="circle_proc"]')))
        WebDriverWait(drive4, 300, 3).until_not(
            EC.visibility_of_element_located((By.XPATH, '//div[@class="circle_proc"]')))
        logging.info("模扫预览加载结束！{}".format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        time.sleep(1)
        drive4.find_element_by_xpath('//button[@class="yg-button default"]').click() #点击确定
        time.sleep(5)
        WebDriverWait(drive4, 300, 3).until_not(
            EC.visibility_of_element_located((By.XPATH, '//div[@class="circle_proc"]')))
        time.sleep(2)
        drive4.find_element_by_xpath('//span[@class="nsel close-btn"]').click()  # 点击模型的叉叉按钮
        WebDriverWait(drive4, 120, 3).until(EC.visibility_of_element_located((By.XPATH, '//div[text()="已检查"]')))
        drive4.find_element_by_xpath('//div[text()="已检查"]').click()  # 已检查元素
        # try:
        #     loc_upload = (By.XPATH, '//div[contains(text(),"已上传")]')
        #     if WebDriverWait(drive3, 30, 1).until(EC.visibility_of_all_elements_located(loc_upload)):
        #         logging.info('DX上传成功')
        #         global dx_a
        #         dx_a+=1
        #         write_excel(3,3,dx_a)
        # except:
        #     logging.info('DX上传失败')
        #     global dx_b
        #     dx_b += 1
        #     write_excel(3, 4, dx_b)
        logging.info('MS结束时间{}'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        return drive4

    except:
        dics_files = create_test_contexts(path2)
        error_filepath = '{}\\{}.png'.format(dics_files, str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
        # error_filepath = 'E:\\DXscreenshot\\error\\{}.png'.format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S")))  # 存放在
        drive4.save_screenshot(error_filepath)
        global dx_c
        dx_c += 1
        write_excel(4, 5, dx_c)
        logging.error("MS{}进度卡住！！！".format(str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))))
        send_to_dingtalk(DEV_NAME, "MS", i)
        # drive3.quit()


if __name__ == '__main__':
    f = open('./gggg')
    d = f.read()
    d = int(d)
    create_excel(d)
    start_time = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    write_excel(4,0,"开始时间")
    write_excel(4,1,start_time)
    num = 20
    try:
        for x in range(d//num):

            c = login_()
            for i in range(num):
                if c:
                    path1 = get_current_path() + '\\screenshot\\CT' + str(datetime.datetime.now().strftime('%Y%m%d'))
                    path2 = path1 + '\\error'
                    a1 = test_01_CT_shooting(x*num+i+1,c,path1,path2)
                else:
                    break
                if c:
                    path1 = get_current_path() + '\\screenshot\\PX' + str(datetime.datetime.now().strftime('%Y%m%d'))
                    path2 = path1 + '\\error'
                    a2 = test_02_Panoramic_shooting(x*num+i+1,c,path1,path2)
                else:
                    break
                if c:
                    path1 = get_current_path() + '\\screenshot\\DX' + str(datetime.datetime.now().strftime('%Y%m%d'))
                    path2 = path1 + '\\error'
                    a3 = test_03_Head_side_shot(x*num+i+1,c,path1,path2)
                else:
                    break
                if c:
                    path1 = get_current_path() + '\\screenshot\\MS' + str(datetime.datetime.now().strftime('%Y%m%d'))
                    path2 = path1 + '\\error'
                    a4 = test_04_Mode_scanning(x*num+i+1,c,path1,path2)
                else:
                    break
            if c != None:
                c.quit()
            else:
                pass
    except Exception as e:
        logging.info(e)
    # finally:
    #     finally_time = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    #     write_excel(5,0,"停止时间")
    #     write_excel(5,1,finally_time)
    #
    #     yag = yagmail.SMTP(user="1425491509@qq.com", password="ikbfjwjsbqhsieih", host='smtp.qq.com')
    #     rev_email = 'yi.deng@dentalink.com.cn'
    #     rev_email3 = 'ping.liu@fussenct.com'
    #     rev_email4 = 'lingbing.zeng@fussenct.com'
    #
    #     rev_email1 = '1425491509@qq.com'
    #     rev_email2 = 'liang.ding@fussenct.com'
    #     title = '【虚拟驱动】发送附件CBCT测试结果'
    #     contents = ['【虚拟驱动】本机电脑CBCT压力稳定性结果统计']
    #     file_path = FindNewFile().get_new_file('.\\reports')
    #     file_path2 = FindNewFile().get_new_file('.\\logs')

        # yag.send() #收件人邮箱 标题 正文 附件地址
        # yag.send([rev_email1,rev_email2], title, contents, [file_path, file_path2])

